from flask import Blueprint,request,make_response,jsonify,redirect,json
import requests
import random
from application.models.users.user import *
from application.models.users.user import db
from utils.com import get_ali_object
# from db import db
import time
from utils.Myjwt import myjwt
gou_blue = Blueprint("gouwu",__name__)
@gou_blue.route('/tianjia',methods=['POST'])
def tianjia():
    data = json.loads(request.data)
    uid = data['uid']
    kid = data['kid']
    shu = data['count']
    is_check  = 20* int(shu)
    k = Orders.query.filter_by(courseid=kid).first()
    if k:
        if k.courseid == kid:
            return jsonify({'code':400,'msg':'已经购买过了'})
    c = Cart(userid=uid,cid=kid,count=shu,is_check=is_check)
    db.session.add(c)
    db.session.commit()
    return jsonify({'code':200,'msg':'加入购物车成功'})
@gou_blue.route('/gouwuzhan')
def gouwuzhan():
    uid = request.args.get('userid')
    k = Cart.query.filter_by(userid=uid).all()
    list = []
    for i in k:
        o = Course.query.filter_by(id=int(i.cid)).all()
        for i in o:
            list.append({
                'id': i.id,
                'name':i.name,
                'url':i.url,
                'descrip':i.descrip
            })
    print("res",)
    return jsonify({'code':200,'data':list})
@gou_blue.route('/gouwugoumai',methods=['POST'])
def gouwumai():
    data = json.loads(request.data)
    userid = data['userid']
    courseid = data['courseid']
    number = 1
    price = 200
    tmoney = 200
    order_no = str(int(time.time())) + str(userid) + str(random.randint(100, 999))
    k = Orders(order_no=order_no,userid=userid,courseid=courseid,number=number,price=price,tmoney=tmoney,status=1)
    db.session.add(k)
    db.session.commit()
    alipay = get_ali_object()
    query_params = alipay.direct_pay(
        subject=str(userid),  # 商品简单描述
        out_trade_no=order_no,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(tmoney),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({'code': 200, 'url': pay_url})
@gou_blue.route('/callback/')
def call():
    # 接收参数
    data = request.args
    datames = {k:v for k,v in data.items()}
    # 删除字典中key为sign的记录
    sign = datames.pop('sign')
    # 鉴权 订单号 流水号
    pay = get_ali_object()
    flag = pay.verify(datames,sign)
    if flag == True:
        # try:
        order_no = request.args.get('out_trade_no')
        trade_no = request.args.get('trade_no')
        print('lllll',order_no)
        print('22222',trade_no)
        k = Orders.query.filter_by(order_no=order_no).first()
        k.status = 2
        k.trans_no= trade_no
        # d = Cart.query.filter_by(cid=k.courseid).delect()
        # db.session.add(d)
        db.session.commit()
    return redirect("http://localhost:8080/#/gou")
